<template>
    <rx-dialog @handOk="handleSubmit" @cancel="cancel">
        <rx-layout>
            <div slot="center" style="padding-right: 80px">
                <a-form-model ref="form" :model="mdl" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
                    <a-form-model-item :label="i18n('form.currentEn','当前实体')" prop="entId" >
                        <rx-input-button ref="entity" v-model="selectEntity" :placeholder="i18n('form.currentEn','当前实体','select')"
                                         @change="changeEntity" @click="setEntity($event,'current')"></rx-input-button>
                    </a-form-model-item>
                    <a-form-model-item :label="i18n('form.prompt','提示字段')" prop="promptField" >
                       <div style="display: flex">
                           <div style="flex: 1;margin-right: 10px"> <a-select v-model="promptField" :options="getFields(mdl.entId,'current')"></a-select></div>
                           <div><a-tooltip>
                               <span slot="title">{{i18n('useToData','用于多条数据删除时区分不可删除数据')}}</span>
                               <a-icon type="question-circle-o" />
                           </a-tooltip></div>
                       </div>
                    </a-form-model-item>
                    <a-form-model-item :label="i18n('form.assoConfig','关联配置')" prop="relationConfig">
                        <div class="table-operations">
                            <a-button  @click="addRow">{{$ti18('rxList.add', '新增')}}</a-button>
                        </div>
                        <rx-grid
                            ref="relationConfig"
                            :allowRowSelect="true"
                            :multiSelect="true"
                            :bordered="true"
                            style="min-height:500px;"
                            :dataSource="relationConfigs"
                            :columns="columns"
                            :showPage="false"
                        >
                            <span slot="fieldAlias" slot-scope="{text,record,index}">
                                <a-select v-model="record.fieldAlias" :options="getFields(mdl.entId,'current')"></a-select>
                            </span>
                            <span slot="relatedEnt" slot-scope="{text,record,index}">
                                <rx-input-button v-model="record.relatedEnt" :placeholder="i18n('form.relateEntity','关联方实体','select')" @click="setEntity($event,'related')"></rx-input-button>
                            </span>
                            <span slot="relFieldAlias" slot-scope="{text,record,index}">
                                <a-select v-model="record.relFieldAlias" :options="getFields(record.relatedEnt,'related')"></a-select>
                            </span>
                            <span slot="deleteType" slot-scope="{text,record,index}">
                                 <a-select v-model="record.deleteType" >
                                    <a-select-option value="1" :title="i18n('notDelete','不允许删除')">{{i18n('notDelete','不允许删除')}}</a-select-option>
                                    <a-select-option value="2" :title="i18n('notCasDel','允许删除但不允许级联删除')">{{i18n('notCasDel','允许删除但不允许级联删除')}}</a-select-option>
                                    <a-select-option value="3" :title="i18n('delAndCas','允许删除且级联删除')">{{i18n('delAndCas','允许删除且级联删除')}}</a-select-option>
                                </a-select>
                            </span>
                            <span slot="prompt" slot-scope="{text,record,index}">
                                <a-input v-model="record.prompt" ></a-input>
                            </span>
                            <span slot="action" slot-scope="{text,record,index}" class="actionIcons">
                                <span @click.stop="delRelation(index)">{{$ti18('rxList.delBtn','删除')}}</span>
                            </span>
                        </rx-grid>
                    </a-form-model-item>
                </a-form-model>
            </div>
        </rx-layout>
    </rx-dialog>
</template>
<script>
import FormEntRelationApi from '@/api/form/core/formEntRelation'
import {RxDialog, BaseFormModel, RxGrid, Dialog} from "@lowcode/jpaas-common-lib";
import FormDbApi from "@/api/form/bo/formDb";


export default {
    name: 'FormEntRelationEdit',
    mixins: [BaseFormModel],
    components: {
        RxDialog,
    },
    data() {
        return {
            rules: {
                entId: [{required: true, message: this.i18n('form.currentEn','当前实体','select'), trigger: 'change'}],
                promptField: [{required: false, message: this.i18n('form.prompt','提示字段','input'), trigger: 'change'}],
                relationConfig: [{required: false, message: this.i18n('form.assoConfig','关联配置','input'), trigger: 'change'}],
                tableName: [{required: false, message: this.i18n('form.tableName','表名','input'), trigger: 'change'}],
            },
            columns: [
                {title: this.$ti18('rxList.index','序号'), type: 'indexColumn', width: '5%', dataIndex: 'serial', scopedSlots: {customRender: 'serial'}},
                {title: this.i18n('form.currField','当前字段'), dataIndex: 'fieldAlias', width: '15%', scopedSlots: {customRender: 'fieldAlias'}},
                {title: this.i18n('form.relateEntity','关联方实体'), dataIndex: 'relatedEnt', width: '15%', scopedSlots: {customRender: 'relatedEnt'}},
                {title: this.i18n('form.relateField','关联方字段'), dataIndex: 'relFieldAlias', width: '15%', scopedSlots: {customRender: 'relFieldAlias'}},
                {title: this.i18n('form.deleteType','删除类型'), dataIndex: 'deleteType', width: '20%', scopedSlots: {customRender: 'deleteType'}},
                {title: this.i18n('form.promState','提示语句'), dataIndex: 'prompt', width: '25%', scopedSlots: {customRender: 'prompt'}},
                {title: this.$ti18('rxList.action','操作'), width: '5%', dataIndex: 'action', scopedSlots: {customRender: 'action'}}
            ],
            relationConfigs: [],
            selectEntity: "",
            //实体的字段 {entId:[]}
            entField: {},
            //提示字段
            promptField:"",
            labelCol: { span: 2 },
            wrapperCol: { span: 15 },
        }

    },
    methods: {
        i18n(name, text, key) {
            return this.$ti18(name, text, "formEntRelation", key);
        },
        onload_(values) {
            if(!values){
                return;
            }
            this.selectEntity=JSON.stringify({
                value:values.entId,
                text:values.entName
            })
            this.getColumnList(values.entId);
            if(values.relationConfig){
                var relationConfigs=JSON.parse(values.relationConfig);
                //获取关联实体的字段
                for (let i = 0; i < relationConfigs.length; i++) {
                    var relatedEnt=relationConfigs[i].relatedEnt;
                    if(relatedEnt){
                        this.getColumnList(JSON.parse(relatedEnt).value);
                    }
                }
                var self=this;
                setTimeout(function () {
                    if(values.promptField){
                        self.promptField=JSON.parse(values.promptField).value
                    }
                    self.relationConfigs=relationConfigs;
                }, 200);
            }
        },
        get(id) {
            return FormEntRelationApi.get(id);
        },
        save() {
            return FormEntRelationApi.save(this.mdl);
        },
        validForm(){
            //关联配置
            if(!this.relationConfigs || this.relationConfigs.length==0){
                this.$message.warning(this.i18n('configEmpty','关联配置不能为空!'));
                return false;
            }
            var success=true;
            var message="";
            for (let i = 0; i < this.relationConfigs.length; i++) {
                var relationConfigs=this.relationConfigs[i];
                if(!relationConfigs.fieldAlias){
                    message=this.i18n('fieldEmpty','当前字段不能为空!');
                    success=false;
                    break;
                }else if(!relationConfigs.relatedEnt){
                    message=this.i18n('relateEmpty','关联方实体不能为空!');
                    success=false;
                    break;
                }else if(!relationConfigs.relFieldAlias){
                    message=this.i18n('relateField','关联方字段不能为空!');
                    success=false;
                    break;
                }
            }
            if(!success){
                this.$message.warning(message);
                return false;
            }
            this.mdl.relationConfig=JSON.stringify(this.relationConfigs);
            if(this.promptField){
                var field=this.entField[this.mdl.entId].find(item=> item.value==this.promptField);
                if(field){
                    this.mdl.promptField=JSON.stringify(field);
                }
            }
            return success;
        },
        addRow() {
            this.relationConfigs.push({
                fieldAlias: "",
                relatedEnt: "",
                relFieldAlias: "",
                deleteType: "1",
                prompt: "",
            })
        },
        delRelation(index) {
            this.relationConfigs.splice(index,1);
        },
        //设置实体 type:current(当前实体) related(关联实体)
        setEntity(vm,type) {
            let self_ = this;
            Dialog.openBoEntDialog({
                curVm: this, widthHeight: ['900px', '600px']
            }, function (data) {
                //当前方
                if("current"==type){
                    self_.$set(self_.mdl,"entId",data.id);
                    self_.$set(self_.mdl,"entName",data.name);
                    self_.$set(self_.mdl,"tableName",data.tableName);
                }
                vm.setVal(data.id, data.name);
                self_.getColumnList(data.id);
            })
        },
        //获取实体的字段
        getColumnList(entId){
            if(entId && !this.entField[entId]){
                FormDbApi.getBoEntId(entId).then(res => {
                    var columnList = res.columnList.map(item => {
                        return {label: item.comment, value: item.fieldName}
                    });
                    this.$set(this.entField,entId,columnList);
                })
            }
        },
        changeEntity(val) {
            if (!val) {
                this.mdl.entId = "";
                this.mdl.entName = "";
                this.mdl.tableName = "";
            }
        },
        getFields(ent,type){
            if(ent){
                if('current'==type){
                    return this.entField[ent];
                }else {
                    if(ent){
                        if(typeof(ent)=='string'){
                            var entAlias= JSON.parse(ent).value;
                            if(entAlias){
                                return this.entField[entAlias];
                            }
                        }
                    }
                }
            }
            return [];
        }

    }
}
</script>
<style>
.relick a {
    margin-right: 10px;
}

</style>
